package com.example.pingxue.service;

import com.example.pingxue.entity.Selection;
import com.example.pingxue.entity.Student;
import com.example.pingxue.entity.TClass;
import com.example.pingxue.repository.ClassRepository;
import com.example.pingxue.repository.SelectionRepository;
import com.example.pingxue.repository.StudentRepository;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class StudentService {
    private final StudentRepository studentRepository;
    private final ClassRepository classRepository;
    private final SelectionRepository selectionRepository;

    // 行为1：学生选教学班
    @Transactional
    public void selectClass(Long studentId, Long classId) {
        // 1. 加载实体（使用getById避免N+1问题）
        Student student = studentRepository.getById(studentId);
        TClass clazz = classRepository.getById(classId);

        // 2. 业务校验
        if (clazz.getSelections().size() >= clazz.getCapacity()) {
            throw new RuntimeException("班级已满，无法选课");
        }

        boolean alreadySelected = clazz.getSelections().stream()
                .anyMatch(s -> s.getStudent().getId().equals(studentId));
        if (alreadySelected) {
            throw new RuntimeException("已选该班级，无需重复选择");
        }

        // 3. 处理关联关系
        Selection selection = new Selection(student, clazz);
        student.getSelections().add(selection);
        clazz.getSelections().add(selection);

        // 4. 持久化
        selectionRepository.save(selection);
    }

    // 行为2：学生退选教学班
    @Transactional
    public void dropClass(Long studentId, Long classId) {
        Student student = studentRepository.getById(studentId);
        TClass clazz = classRepository.getById(classId);

        // 查找关联记录
        Selection selection = selectionRepository.findByStudentAndClazz(student, clazz)
                .orElseThrow(() -> new EntityNotFoundException("未找到选课记录"));

        // 移除关联
        student.getSelections().remove(selection);
        clazz.getSelections().remove(selection);

        // 逻辑删除（而非物理删除）
        selection.setIsDeleted(true);
        selectionRepository.save(selection);
    }

    // 行为6：学生查看课程表
    public Set<TClass> getCourseSchedule(Long studentId) {
        Student student = studentRepository.findById(studentId)
                .orElseThrow(() -> new EntityNotFoundException("学生不存在"));

        // 使用延迟加载并转换结果
        return student.getSelections().stream()
                .map(Selection::getClazz)
                .collect(Collectors.toSet());
    }
}
